<!DOCTYPE html>
<html xmlns:th="http://www.thymeleaf.org" lang="zh-CN">

<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>个人信息 - 教学管理系统</title>
    <style>
        body {
            font-family: 'Microsoft YaHei', sans-serif;
            background-color: #f5f5f5;
            margin: 0;
            padding: 0;
        }

        .container {
            display: flex;
            min-height: 100vh;
        }

        .sidebar {
            width: 250px;
            background-color: #2c3e50;
            color: white;
            padding-top: 20px;
        }

        .sidebar-header {
            padding: 0 20px 20px;
            border-bottom: 1px solid #3c5166;
        }

        .sidebar-header h2 {
            margin: 0;
            font-size: 20px;
        }

        .user-info {
            margin-top: 10px;
            font-size: 14px;
            opacity: 0.8;
        }

        .menu {
            list-style: none;
            padding: 0;
            margin: 20px 0;
        }

        .menu li {
            padding: 12px 20px;
            cursor: pointer;
            transition: background-color 0.3s;
        }

        .menu li:hover {
            background-color: #3c5166;
        }

        .menu li.active {
            background-color: #3498db;
        }

        .menu a {
            color: white;
            text-decoration: none;
            display: block;
        }

        .content {
            flex: 1;
            padding: 20px;
        }

        .content-header {
            margin-bottom: 30px;
        }

        .content-header h1 {
            margin: 0;
            color: #333;
            font-size: 24px;
        }

        .profile-container {
            display: flex;
            gap: 30px;
        }

        .profile-sidebar {
            width: 250px;
        }

        .profile-avatar {
            background-color: white;
            border-radius: 8px;
            box-shadow: 0 2px 10px rgba(0, 0, 0, 0.1);
            padding: 20px;
            text-align: center;
            margin-bottom: 20px;
        }

        .avatar-img {
            width: 150px;
            height: 150px;
            border-radius: 50%;
            background-color: #ecf0f1;
            display: flex;
            align-items: center;
            justify-content: center;
            margin: 0 auto 15px;
            overflow: hidden;
            border: 3px solid #3498db;
        }

        .avatar-img img {
            width: 100%;
            height: 100%;
            object-fit: cover;
        }

        .avatar-placeholder {
            font-size: 60px;
            color: #7f8c8d;
        }

        .avatar-name {
            font-size: 18px;
            font-weight: bold;
            color: #2c3e50;
            margin-bottom: 5px;
        }

        .avatar-role {
            color: #7f8c8d;
            font-size: 14px;
        }

        .profile-menu {
            background-color: white;
            border-radius: 8px;
            box-shadow: 0 2px 10px rgba(0, 0, 0, 0.1);
            overflow: hidden;
        }

        .profile-menu-item {
            padding: 15px 20px;
            cursor: pointer;
            transition: background-color 0.3s;
            border-bottom: 1px solid #ecf0f1;
        }

        .profile-menu-item:last-child {
            border-bottom: none;
        }

        .profile-menu-item.active {
            background-color: #3498db;
            color: white;
            font-weight: bold;
        }

        .profile-menu-item:hover:not(.active) {
            background-color: #f5f7fa;
        }

        .profile-content {
            flex: 1;
        }

        .profile-section {
            background-color: white;
            border-radius: 8px;
            box-shadow: 0 2px 10px rgba(0, 0, 0, 0.1);
            padding: 25px;
            margin-bottom: 20px;
        }

        .profile-section h2 {
            margin-top: 0;
            margin-bottom: 20px;
            color: #2c3e50;
            font-size: 18px;
            border-bottom: 1px solid #ecf0f1;
            padding-bottom: 10px;
        }

        .info-grid {
            display: grid;
            grid-template-columns: repeat(2, 1fr);
            gap: 20px;
        }

        .info-item {
            margin-bottom: 15px;
        }

        .info-label {
            font-size: 14px;
            color: #7f8c8d;
            margin-bottom: 5px;
        }

        .info-value {
            font-size: 16px;
            color: #2c3e50;
            font-weight: 500;
        }

        .form-group {
            margin-bottom: 20px;
        }

        .form-group label {
            display: block;
            margin-bottom: 5px;
            font-size: 14px;
            color: #7f8c8d;
        }

        .form-control {
            width: 100%;
            padding: 10px;
            border: 1px solid #ddd;
            border-radius: 4px;
            font-size: 14px;
        }

        .form-control:focus {
            border-color: #3498db;
            outline: none;
        }

        .btn {
            padding: 10px 15px;
            border: none;
            border-radius: 4px;
            cursor: pointer;
            font-size: 14px;
            transition: background-color 0.3s;
        }

        .btn-primary {
            background-color: #3498db;
            color: white;
        }

        .btn-primary:hover {
            background-color: #2980b9;
        }

        .btn-danger {
            background-color: #e74c3c;
            color: white;
        }

        .btn-danger:hover {
            background-color: #c0392b;
        }

        .form-buttons {
            display: flex;
            justify-content: flex-end;
            gap: 10px;
            margin-top: 20px;
        }

        .hidden {
            display: none;
        }

        .alert {
            padding: 12px 15px;
            margin-bottom: 20px;
            border-radius: 4px;
            color: white;
        }

        .alert-success {
            background-color: #27ae60;
        }

        .alert-danger {
            background-color: #e74c3c;
        }

        .logout {
            margin-top: auto;
            padding: 20px;
        }

        .logout a {
            color: #e74c3c;
            text-decoration: none;
        }
    </style>
</head>

<body>
    <div class="container">
        <div class="sidebar">
            <div class="sidebar-header">
                <h2>教学管理系统</h2>
                <div class="user-info" th:if="${session.user}">
                    <span id="sidebar-student-name">学生</span> - <span th:text="${session.user.role}">学生</span>
                </div>
            </div>
            <ul class="menu">
                <li><a href="/student/dashboard">我的概览</a></li>
                <li><a href="/student/courses">选课中心</a></li>
                <li><a href="/student/schedule">我的课表</a></li>
                <li><a href="/student/grades">我的成绩</a></li>
                <li class="active"><a href="/student/profile">个人信息</a></li>
            </ul>
            <div class="logout">
                <a href="/logout">退出登录</a>
            </div>
        </div>

        <div class="content">
            <div class="content-header">
                <h1>个人信息</h1>
            </div>

            <div class="profile-container">
                <div class="profile-sidebar">
                    <div class="profile-avatar">
                        <div class="avatar-img">
                            <img id="profile-image" src="/images/p1.jpg" alt="Profile Picture">
                        </div>
                        <div class="avatar-name" id="student-name">加载中...</div>
                        <div class="avatar-role">学生</div>
                    </div>

                    <div class="profile-menu">
                        <div class="profile-menu-item active" data-section="basic-info">基本信息</div>
                        <div class="profile-menu-item" data-section="change-password">修改密码</div>
                    </div>
                </div>

                <div class="profile-content">
                    <!-- 基本信息部分 -->
                    <div class="profile-section" id="basic-info-section">
                        <h2>基本信息</h2>
                        <div id="alert-container-basic" class="hidden alert"></div>

                        <div class="info-grid">
                            <div class="info-item">
                                <div class="info-label">学号</div>
                                <div class="info-value" id="student-id">-</div>
                            </div>
                            <div class="info-item">
                                <div class="info-label">姓名</div>
                                <div class="info-value" id="student-fullname">-</div>
                            </div>
                            <div class="info-item">
                                <div class="info-label">性别</div>
                                <div class="info-value" id="student-gender">-</div>
                            </div>
                            <div class="info-item">
                                <div class="info-label">出生日期</div>
                                <div class="info-value" id="student-birth-date">-</div>
                            </div>
                            <div class="info-item">
                                <div class="info-label">专业</div>
                                <div class="info-value" id="student-major">-</div>
                            </div>
                            <div class="info-item">
                                <div class="info-label">年级</div>
                                <div class="info-value" id="student-grade">-</div>
                            </div>
                            <div class="info-item">
                                <div class="info-label">入学日期</div>
                                <div class="info-value" id="student-enrollment-date">-</div>
                            </div>
                            <div class="info-item">
                                <div class="info-label">用户名</div>
                                <div class="info-value" id="student-username">-</div>
                            </div>
                        </div>

                        <div class="form-buttons">
                            <button class="btn btn-primary" id="edit-info-btn">编辑信息</button>
                        </div>
                    </div>

                    <!-- 编辑基本信息部分 -->
                    <div class="profile-section hidden" id="edit-info-section">
                        <h2>编辑基本信息</h2>
                        <div id="alert-container-edit" class="hidden alert"></div>

                        <form id="edit-info-form">
                            <div class="info-grid">
                                <div class="form-group">
                                    <label for="edit-name">姓名</label>
                                    <input type="text" id="edit-name" class="form-control" required>
                                </div>
                                <div class="form-group">
                                    <label for="edit-gender">性别</label>
                                    <select id="edit-gender" class="form-control" required>
                                        <option value="男">男</option>
                                        <option value="女">女</option>
                                    </select>
                                </div>
                                <div class="form-group">
                                    <label for="edit-birth-date">出生日期</label>
                                    <input type="date" id="edit-birth-date" class="form-control" required>
                                </div>
                                <div class="form-group">
                                    <label for="edit-username">用户名</label>
                                    <input type="text" id="edit-username" class="form-control" required>
                                </div>
                            </div>

                            <div class="form-buttons">
                                <button type="button" class="btn" id="cancel-edit-btn">取消</button>
                                <button type="submit" class="btn btn-primary">保存</button>
                            </div>
                        </form>
                    </div>

                    <!-- 修改密码部分 -->
                    <div class="profile-section hidden" id="change-password-section">
                        <h2>修改密码</h2>
                        <div id="alert-container-password" class="hidden alert"></div>

                        <form id="change-password-form">
                            <div class="form-group">
                                <label for="current-password">当前密码</label>
                                <input type="password" id="current-password" class="form-control" required>
                            </div>
                            <div class="form-group">
                                <label for="new-password">新密码</label>
                                <input type="password" id="new-password" class="form-control" required>
                            </div>
                            <div class="form-group">
                                <label for="confirm-password">确认新密码</label>
                                <input type="password" id="confirm-password" class="form-control" required>
                            </div>

                            <div class="form-buttons">
                                <button type="submit" class="btn btn-primary">修改密码</button>
                            </div>
                        </form>
                    </div>
                </div>
            </div>
        </div>
    </div>

    <!-- 存储会话中的用户名 -->
    <input type="hidden" id="session-username" th:value="${session.user != null ? session.user.username : ''}">

    <script>
        document.addEventListener('DOMContentLoaded', function () {
            // 获取学生信息
            fetchStudentInfo();

            // 侧边栏菜单切换
            const menuItems = document.querySelectorAll('.profile-menu-item');
            const sections = document.querySelectorAll('.profile-section');

            menuItems.forEach(item => {
                item.addEventListener('click', function () {
                    const target = this.getAttribute('data-section');

                    // 激活当前菜单项
                    menuItems.forEach(i => i.classList.remove('active'));
                    this.classList.add('active');

                    // 显示对应的内容区域
                    sections.forEach(section => {
                        section.classList.add('hidden');
                    });

                    if (target === 'basic-info') {
                        document.getElementById('basic-info-section').classList.remove('hidden');
                        // 显示面板时隐藏编辑面板
                        document.getElementById('edit-info-section').classList.add('hidden');
                    } else if (target === 'change-password') {
                        document.getElementById('change-password-section').classList.remove('hidden');
                    }
                });
            });

            // 编辑按钮点击事件
            document.getElementById('edit-info-btn').addEventListener('click', function () {
                document.getElementById('basic-info-section').classList.add('hidden');
                document.getElementById('edit-info-section').classList.remove('hidden');

                // 填充表单
                document.getElementById('edit-name').value = document.getElementById('student-fullname').textContent;
                document.getElementById('edit-gender').value = document.getElementById('student-gender').textContent;

                // 格式化日期为YYYY-MM-DD
                const birthDateText = document.getElementById('student-birth-date').textContent;
                if (birthDateText !== '-') {
                    const birthDate = new Date(birthDateText);
                    const formattedDate = birthDate.toISOString().split('T')[0];
                    document.getElementById('edit-birth-date').value = formattedDate;
                }

                document.getElementById('edit-username').value = document.getElementById('student-username').textContent;
            });

            // 取消编辑按钮点击事件
            document.getElementById('cancel-edit-btn').addEventListener('click', function () {
                document.getElementById('edit-info-section').classList.add('hidden');
                document.getElementById('basic-info-section').classList.remove('hidden');
            });

            // 编辑信息表单提交
            document.getElementById('edit-info-form').addEventListener('submit', function (e) {
                e.preventDefault();
                updateStudentInfo();
            });

            // 修改密码表单提交
            document.getElementById('change-password-form').addEventListener('submit', function (e) {
                e.preventDefault();
                changePassword();
            });
        });

        // 获取学生信息
        function fetchStudentInfo() {
            fetch('/api/student/info')
                .then(response => {
                    if (!response.ok) {
                        if (response.status === 401) {
                            alert('未授权，请重新登录');
                            window.location.href = '/login';
                            throw new Error('未授权');
                        }
                        return response.text().then(text => { throw new Error(text || '获取学生信息失败') });
                    }
                    return response.json();
                })
                .then(student => {
                    // 更新页面显示
                    document.getElementById('student-name').textContent = student.name;
                    document.getElementById('sidebar-student-name').textContent = student.name;
                    document.getElementById('student-id').textContent = student.studentId;
                    document.getElementById('student-fullname').textContent = student.name;
                    document.getElementById('student-gender').textContent = student.gender;
                    document.getElementById('student-birth-date').textContent = formatDate(student.birthDate);
                    document.getElementById('student-major').textContent = student.major;
                    document.getElementById('student-grade').textContent = student.grade;
                    document.getElementById('student-enrollment-date').textContent = formatDate(student.enrollmentDate);

                    // 首先尝试从隐藏输入中获取用户名
                    const sessionUsername = document.getElementById('session-username').value;
                    if (sessionUsername && sessionUsername.trim() !== '') {
                        document.getElementById('student-username').textContent = sessionUsername;
                    } else {
                        // 如果隐藏输入中没有用户名，则尝试从API获取
                        fetch(`/api/student/username/${student.studentId}`)
                            .then(response => {
                                if (!response.ok) {
                                    throw new Error('获取用户名失败');
                                }
                                return response.json();
                            })
                            .then(data => {
                                document.getElementById('student-username').textContent = data.username;
                            })
                            .catch(error => {
                                console.error('获取用户名失败:', error);
                                document.getElementById('student-username').textContent = student.studentId;
                            });
                    }
                })
                .catch(error => {
                    console.error('获取学生信息失败:', error);
                    alert('获取学生信息失败: ' + error.message);
                });
        }

        // 更新学生信息
        function updateStudentInfo() {
            const updatedInfo = {
                name: document.getElementById('edit-name').value,
                gender: document.getElementById('edit-gender').value,
                birthDate: document.getElementById('edit-birth-date').value,
                username: document.getElementById('edit-username').value
            };

            // 显示处理中状态
            showAlert('alert-container-edit', '正在提交更新...', 'info');

            fetch('/api/student/update', {
                method: 'PUT',
                headers: {
                    'Content-Type': 'application/json'
                },
                body: JSON.stringify(updatedInfo)
            })
                .then(response => {
                    if (!response.ok) {
                        if (response.status === 401) {
                            alert('未授权，请重新登录');
                            window.location.href = '/login';
                            throw new Error('未授权');
                        }
                        return response.text().then(text => {
                            // 尝试解析错误消息
                            try {
                                return Promise.reject(new Error(text || '更新信息失败'));
                            } catch (e) {
                                return Promise.reject(new Error('更新信息失败'));
                            }
                        });
                    }
                    return response.json();
                })
                .then(data => {
                    showAlert('alert-container-edit', '信息更新成功！', 'success');

                    // 更新页面显示
                    document.getElementById('student-name').textContent = updatedInfo.name;
                    document.getElementById('sidebar-student-name').textContent = updatedInfo.name;
                    document.getElementById('student-fullname').textContent = updatedInfo.name;
                    document.getElementById('student-gender').textContent = updatedInfo.gender;
                    document.getElementById('student-birth-date').textContent = formatDate(updatedInfo.birthDate);
                    document.getElementById('student-username').textContent = updatedInfo.username;

                    // 延迟返回信息面板
                    setTimeout(() => {
                        document.getElementById('edit-info-section').classList.add('hidden');
                        document.getElementById('basic-info-section').classList.remove('hidden');
                    }, 1500);
                })
                .catch(error => {
                    console.error('更新学生信息失败:', error);
                    showAlert('alert-container-edit', '更新失败: ' + error.message, 'danger');
                });
        }

        // 修改密码
        function changePassword() {
            const currentPassword = document.getElementById('current-password').value;
            const newPassword = document.getElementById('new-password').value;
            const confirmPassword = document.getElementById('confirm-password').value;

            // 密码确认
            if (newPassword !== confirmPassword) {
                showAlert('alert-container-password', '两次输入的新密码不一致', 'danger');
                return;
            }

            const passwordData = {
                currentPassword: currentPassword,
                newPassword: newPassword
            };

            fetch('/api/student/change-password', {
                method: 'PUT',
                headers: {
                    'Content-Type': 'application/json'
                },
                body: JSON.stringify(passwordData)
            })
                .then(response => {
                    if (!response.ok) {
                        if (response.status === 401) {
                            return response.text().then(text => { throw new Error(text || '当前密码错误') });
                        }
                        return response.text().then(text => { throw new Error(text || '修改密码失败') });
                    }
                    return response.text();
                })
                .then(data => {
                    showAlert('alert-container-password', '密码修改成功！', 'success');
                    document.getElementById('change-password-form').reset();
                })
                .catch(error => {
                    console.error('修改密码失败:', error);
                    showAlert('alert-container-password', '修改失败: ' + error.message, 'danger');
                });
        }

        // 显示提示信息
        function showAlert(containerId, message, type) {
            const container = document.getElementById(containerId);
            container.textContent = message;
            container.className = `alert alert-${type}`;

            // 5秒后自动隐藏
            setTimeout(() => {
                container.className = 'hidden alert';
            }, 5000);
        }

        // 格式化日期
        function formatDate(dateString) {
            if (!dateString) return '-';
            const date = new Date(dateString);
            return date.getFullYear() + '-' +
                (date.getMonth() + 1).toString().padStart(2, '0') + '-' +
                date.getDate().toString().padStart(2, '0');
        }
    </script>
</body>

</html>